// components/Ueditor/index.js

import React from 'react';
import { Button, Modal, InputNumber, Input, Select, Form } from 'antd';
import TheButton from "@/components/TheButton";

// import api from '@/api';
const UE = window.UE;
class UEditor extends React.Component {
    constructor(props) {
        super(props);
        this.formRefs = React.createRef()
        this.state = {
            content: '',
            editor: '',
            isModalVisible: false,
            image_width: 0,
            image_height: 0,
            goodId: '',
            storeId: '',
            navType: ''
        };
        this.timer = null;
    }

    componentDidMount() {
        console.log(12355);
        setTimeout(() => {
            this.initEditor()
        }, 100);
    }

    componentWillUnmount() {
        // 组件卸载后，清除放入库的id
        if (typeof (UE.getEditor(this.props.id)) != 'undefined') {
            UE.getEditor(this.props.id).destroy();
            clearTimeout(this.timer)
        }
    }

    initEditor() {
        /*初始化编辑器*/
        const { id, contentChange, initialFrameHeight, content } = this.props;
        const ueEditor = UE.getEditor(this.props.id, {
            // 编辑器不自动被内容撑高
            autoHeightEnabled: false,
            // 初始容器高度
            initialFrameHeight: initialFrameHeight || 300,
            // 初始容器宽度
            initialFrameWidth: '410',
        });

        const self = this;

        ueEditor.addListener('contentChange', () => {
            contentChange(self.getVal())
        });


        ueEditor.commands['hqm'] = {
            execCommand: function (cmdName) {
                self.setState({
                    isModalVisible: true
                })
            }
        };
        ueEditor.ready((ueditor) => {
            if (!ueditor) {
                UE.delEditor(id);
                self.initEditor();
            }
        });

        let editor = ueEditor;
        this.setState({ editor });
    }
    setVal(con) {
        let { editor } = this.state;
        editor.ready((ueditor) => {
            if (ueditor) {
                con = con.replace(/video-js\" src/gi, "\" _url")
                con = con.replace(/<video/gi, "<img src='/manage/ueditor/themes/default/images/spacer.gif' style='background:url(/manage/ueditor/themes/default/images/videologo.gif) no-repeat center center; border:1px solid gray;'")
                con = con.replace(/<\/video>/gi, "</img>")
                editor.setContent(con);
                clearTimeout(this.timer)
            }
        });
        this.timer = setTimeout(function () {
            editor.setContent(con);
        }, 700)
    }
    getVal() {
        let { editor } = this.state;
        let content = editor.getContent();
        return content;
    }

    handleCancel = () => {
        this.formRefs.current.resetFields()
        this.setState({
            isModalVisible: false,
        })
    }

    handleOk = () => {

        this.formRefs.current.validateFields().then(values => {
            console.log(values, 'aaa');
            const _this = this
            this.formRefs.current.resetFields()
            this.setState({
                isModalVisible: false
            }, () => {

                const _this = this;
                const input = document.createElement('input')
                input.type = 'file'
                input.click()
                input.onchange = (e) => {
                    let formData = new FormData();
                    formData.append("file", e.target.files[0]);
                    fetch(React.$BaseUrl + '/admin/oss/image/upload',
                        {
                            method: "post",
                            headers: {
                                RSnetToken: sessionStorage.getItem('RSnetToken')
                            },
                            body: formData,
                        })
                        .then((res) => {
                            res.json().then(result => {
                                if (result.code === 0) {
                                    const { code, data, codeMessage
                                    } = result
                                    const { image_width, image_height, goodId, storeId, navType, activityId, couponId } = values

                                    if (code === 0) {
                                        let editor = _this.state.editor;
                                        editor.execCommand('insertHtml',
                                            `<img id="hqmImage" data-couponId="${couponId}" data-activityId="${activityId}" data-type="${navType}" data-goodId="${goodId}" data-storeId="${storeId}" src="${data}" width="${image_width}%" ${image_height ? 'height="' + image_height + 'px"' : ''}/>`);
                                    }
                                }
                            })
                        })
                }
            })
        })
    }

    render() {
        let { content, id } = this.props;
        let { isModalVisible } = this.state
        return (
            <React.Fragment>
                <textarea id={id}
                    defaultValue={content}
                    style={{ width: 0, height: 0 }}
                    onChange={this.getVal} />
                <Modal title="图片上传" visible={isModalVisible} onOk={this.handleOk} onCancel={this.handleCancel}>
                    {
                        isModalVisible &&
                        <Form
                            name="basic"
                            ref={this.formRefs}
                            labelCol={{
                                span: 6,
                            }}
                            wrapperCol={{
                                span: 16,
                            }}
                            onFinish={this.onFinish}
                        >
                            <Form.Item
                                label="宽度（%）"
                                name="image_width"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入',
                                    },
                                ]}
                            >
                                <InputNumber max={100} min={0} />
                            </Form.Item>

                            <Form.Item
                                label="高度（像素）"
                                name="image_height"
                            >
                                <InputNumber min={0} />
                            </Form.Item>

                            <Form.Item
                                label="类型"
                                name="navType"

                            >
                                <Select allowClear options={
                                    [{ label: '跳转', value: 'nav' }, { label: '商品详情', value: 'good' }, { label: '优惠券', value: 'coupon' }]
                                } />
                            </Form.Item>
                            <Form.Item
                                noStyle
                                shouldUpdate={(prevValues, currentValues) => prevValues.navType !== currentValues.navType}

                            >{
                                    ({ getFieldValue }) =>
                                        ['good'].includes(getFieldValue('navType')) ? (
                                            <>
                                                <Form.Item
                                                    label="商品id"
                                                    name="goodId"
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请输入',
                                                        },
                                                    ]}
                                                >
                                                    <Input />
                                                </Form.Item>

                                                <Form.Item
                                                    label="店铺id"
                                                    name="storeId"
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请输入',
                                                        },
                                                    ]}
                                                >
                                                    <Input />
                                                </Form.Item></>

                                        ) : ['nav'].includes(getFieldValue('navType')) ?
                                            <Form.Item
                                                label="活动Id"
                                                name="activityId"
                                                rules={[
                                                    {
                                                        required: true,
                                                        message: '请输入',
                                                    },
                                                ]}
                                            >
                                                <Input />
                                            </Form.Item>

                                            : ['coupon'].includes(getFieldValue('navType')) ?
                                                <Form.Item
                                                    label="优惠券Id"
                                                    name="couponId"
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请输入',
                                                        },
                                                    ]}
                                                >
                                                    <Input />
                                                </Form.Item> : null}


                            </Form.Item>

                        </Form>


                    }
                </Modal>
            </React.Fragment>
        )
    }
}
export default UEditor;

